/*
 * @lc app=leetcode.cn id=1382 lang=typescript
 *
 * [1382] 将二叉搜索树变平衡
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function inorder(root: TreeNode | null, seq: TreeNode[]) {
  if (root === null) return;
  inorder(root.left, seq);
  seq.push(root);
  inorder(root.right, seq);
  return seq;
}

function build(seq: TreeNode[], l: number, r: number): TreeNode | null {
  if (l > r) return null;
  // 每次使用中间节点来当作根节点
  let mid = (l + r) >> 1;
  const root = seq[mid];
  // 遍历这个过程
  root.left = build(seq, l, mid - 1);
  root.right = build(seq, mid + 1, r);
  return root;
}

function balanceBST(root: TreeNode | null): TreeNode | null {
  // 获得中序遍历序列
  const inorderSeq = inorder(root, []);

  return build(inorderSeq, 0, inorderSeq.length - 1);
}
// @lc code=end
